package com.markbuikema.juliana32.asynctask;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;

import com.markbuikema.juliana32.model.nieuws.FacebookNieuwsItem;
import com.markbuikema.juliana32.model.nieuws.NieuwsItem;
import com.markbuikema.juliana32.model.nieuws.WebsiteNieuwsItem;
import com.markbuikema.juliana32.util.DateTimeUtils;
import com.markbuikema.juliana32.util.facebook.FacebookManager;

public abstract class NieuwsRetriever extends AsyncTask<String, NieuwsItem, List<NieuwsItem>> {

	private static final String TAG = "NieuwsRetriever";
	public static final String GET_URL = "http://www.svjuliana32.nl/wp-json/posts";
	public static final String GET_URL_SEARCH = "http://www.svjuliana32.nl/wp-json/posts?filter[s]=%s";
	private String statusCode;
	private boolean retrieveFromFacebook;
	private boolean retrieveFromWebsite;

	public NieuwsRetriever(boolean facebook, boolean website) {
		retrieveFromFacebook = facebook;
		retrieveFromWebsite = website;
	}

	@Override
	protected List<NieuwsItem> doInBackground(String... params) {
		String searchWord = null;
		if (params.length > 0) {
			searchWord = params[0].toLowerCase();
		}

		// Log.d("nieuwsloader", "1");
		final ArrayList<NieuwsItem> items = new ArrayList<NieuwsItem>();

		if (retrieveFromWebsite) {
			try {
				HttpParams faster = new BasicHttpParams();
				faster.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
				
				HttpClient client = new DefaultHttpClient(faster);
				HttpGet get = new HttpGet(searchWord == null ? GET_URL : String.format(GET_URL_SEARCH, URLEncoder.encode(searchWord, "UTF-8")));
				// Log.d("nieuwsloader", "2");

				HttpResponse response = client.execute(get);
				// Log.d("nieuwsloader", "3");
				statusCode = Integer.toString(response.getStatusLine().getStatusCode());
				if (!statusCode.startsWith("2"))
					return null;
				String jsonString = null;
				jsonString = EntityUtils.toString(response.getEntity(), "UTF-8");

				JSONArray json = new JSONArray(jsonString);
				for (int i = 0; i < json.length(); i++) {
					JSONObject object = json.getJSONObject(i);
					String id = object.optString("ID");
					String subTitle = object.optString("excerpt").replace("&nbsp;", " ");
					String title = object.optString("title").replace("&nbsp;", " ");
					String content = object.optString("content").replace("&nbsp;", " ");
					GregorianCalendar createdAt = DateTimeUtils.fbStringToDate(object.optString("date"));
					String detailUrl = object.optString("link");

					NieuwsItem item = new WebsiteNieuwsItem(id, title, subTitle, content, createdAt, detailUrl);
					items.add(item);
				}

			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if (retrieveFromFacebook) {
			List<FacebookNieuwsItem> fbItems = FacebookManager.getInstance().getFacebookFeed();
			if (searchWord == null) {
				items.addAll(fbItems);
			} else {
				for (FacebookNieuwsItem fbi : fbItems) {
					String content = fbi.getContent() == null ? "" : fbi.getContent().toLowerCase();
					String subtitle = fbi.getSubTitle() == null ? "" : fbi.getSubTitle().toLowerCase();
					if (content.contains(searchWord) || subtitle.contains(searchWord))
						items.add(fbi);
				}
			}
		}

		Collections.sort(items);
		return items;
	}
}